<template>
  <el-form :model="form" :rules="rules" @submit.prevent="submitForm">
    <div class="space-y-12">
      <div class="devider-line">
        <h2 class="text-base font-semibold leading-7 text-gray-900">
          {{ t('appPageTitle.profileSettings') }}
        </h2>
        <p class="mt-1 small-text">
          {{ t('pageProfileSettings.discription') }}
        </p>

        <div class="mt-2 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
          <div class="sm:col-span-4">
            <label
              for="username"
              class="text-base font-semibold leading-7 text-gray-900"
              >{{ t('pageProfileSettings.username') }}</label
            >
            <el-form-item prop="username">
              <el-input
                type="text"
                v-model="form.username"
                name="username"
                id="username"
                class="element-input"
                @focus="v$.username.$touch()"
                disabled
              />
            </el-form-item>
          </div>
        </div>
      </div>

      <div class="devider-line">
        <div class="mt-5 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
          <div class="sm:col-span-4">
            <label
              for="username"
              class="text-base font-semibold leading-7 text-gray-900"
              >{{ $t('pageProfileSettings.newPassword') }}</label
            >
            <el-form-item prop="newPassword">
              <el-input
                type="text"
                v-model="form.newPassword"
                class="element-input"
              />
            </el-form-item>
          </div>
        </div>
        <div class="mt-1 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
          <div class="sm:col-span-4">
            <label
              for="username"
              class="text-base font-semibold leading-7 text-gray-900"
              >{{ $t('pageProfileSettings.confirmPassword') }}</label
            >
            <el-form-item prop="confirmPassword">
              <el-input
                type="text"
                v-model="form.confirmPassword"
                class="element-input"
                @focus="v$.newPassword.$touch()"
              />
            </el-form-item>
          </div>
        </div>
      </div>

      <div class="devider-line">
        <div class="mt-10 space-y-10">
          <fieldset>
            <legend class="text-sm font-semibold leading-6 text-gray-900">
              {{ t('pageProfileSettings.timezoneDisplay') }}
            </legend>
            <p class="mt-1 small-text">
              {{ t('pageProfileSettings.timezoneDisplayDesc') }}
            </p>
            <div class="mt-6 space-y-6">
              <div class="flex items-center gap-x-3">
                <input
                  id="timezone-display-option1"
                  name="timezone-display"
                  type="radio"
                  class="option-item"
                  :checked="form.isUtcDisplay"
                  v-model="form.isUtcDisplay"
                  :value="true"
                />
                <label
                  for="timezone-display-option1"
                  class="block text-sm font-medium leading-6 text-gray-900"
                  >{{ t('pageProfileSettings.defaultUTC') }}</label
                >
              </div>
              <div class="flex items-center gap-x-3">
                <input
                  id="timezone-display-option2"
                  name="timezone-display"
                  type="radio"
                  class="option-item"
                  :checked="!form.isUtcDisplay"
                  v-model="form.isUtcDisplay"
                  :value="false"
                />
                <label
                  for="timezone-display-option2"
                  class="block text-sm font-medium leading-6 text-gray-900"
                  >{{
                    t('pageProfileSettings.browserOffset', {
                      timezone,
                    })
                  }}</label
                >
              </div>
            </div>
          </fieldset>
        </div>
      </div>
    </div>

    <div class="mt-6 flex items-center justify-end gap-x-6">
      <button
        type="button"
        class="cancel-button"
        @click="
          () => {
            $router.go(0);
          }
        "
      >
        {{ t('global.action.cancel') }}
      </button>
      <button type="submit" class="submit-button">
        {{ t('global.action.save') }}
      </button>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { useGlobalStore } from '@/store/global';
import { useUserManagementStore } from '@/store/UserSecurity/UserManagement/UserManagementStore';
import { useI18n } from 'vue-i18n';
import useLocalTimeZone from '@/hooks/useLocalTimezoneLabel';
import useVuelidateTool from '@/hooks/useVuelidateTool';

const { localOffset } = useLocalTimeZone();
const {
  useVuelidate,
  required,
  minLength,
  maxLength,
  sameAs,
  elementInputValidator,
} = useVuelidateTool();

const globalStore = useGlobalStore();
const userManagementStore = useUserManagementStore();

const i18n = reactive(useI18n());
const { t } = toRefs(i18n);

const timezone = computed(() => localOffset());

const form = reactive({
  username: globalStore.username,
  newPassword: '',
  confirmPassword: '',
  isUtcDisplay: globalStore.isUtcDisplay,
});

const newpassword = toRef(form, 'newPassword');

const v$ = useVuelidate(
  {
    username: {
      required,
    },
    newPassword: {
      required,
      minLength: minLength(6),
      maxLength: maxLength(16),
    },
    confirmPassword: {
      required,
      minLength: minLength(6),
      maxLength: maxLength(16),
      confirmPassword: sameAs(newpassword),
    },
  },
  form,
);

const rules = computed(() => {
  return {
    username: [
      {
        trigger: 'blur',
        validator: elementInputValidator.value(v$, 'username'),
      },
    ],
    newPassword: [
      {
        trigger: 'blur',
        validator: elementInputValidator.value(v$, 'newPassword'),
      },
    ],
    confirmPassword: [
      {
        trigger: 'blur',
        validator: elementInputValidator.value(v$, 'confirmPassword'),
      },
    ],
  };
});

const saveNewPasswordInputData = () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  let userData = {
    originalUsername: form.username,
    password: form.newPassword,
  };
  userManagementStore
    .updateUser(userData)
    .then((message: string) => {
      (form.newPassword = ''), (form.confirmPassword = '');
      v$.value.$reset();
      ElNotification({
        title: 'Success',
        message: message,
        type: 'success',
      });
    })
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message: message,
        type: 'error',
      }),
    );
};

const saveTimeZonePrefrenceData = () => {
  localStorage.setItem('storedUtcDisplay', form.isUtcDisplay);
  globalStore.setUtcTime(form.isUtcDisplay);
  ElNotification({
    title: 'Success',
    message: t.value('pageProfileSettings.toast.successSaveSettings'),
    type: 'success',
  });
};

const submitForm = () => {
  if (form.confirmPassword || form.newPassword) {
    saveNewPasswordInputData();
  }
  saveTimeZonePrefrenceData();
};
</script>
